App.controller("setTaskCtrl",function($scope, $rootScope, $location, $http, $compile, $stateParams, $timeout, path, publicService) {
	
	$scope.search = {};		//搜索参数
	$scope.form = {};		//表单参数
	
	var guiderTree = null		//导购树;		
	var guiderDataList = null;	//导购数据; 
	
	var alertModel = {};	//alert模态框
	
	//提示信息
	$scope.alertMessage = function(message){
		alertModel.pannel = jqueryAlert({
			content: message,
			modal: true
		});
	}
	
	
	//表格对象
	$scope.gridOptions = {
			dataSource : {
				transport : {
					read : {
						url : path+"/server/selectUserActivity",
						type : 'POST',
						dataType : "json",
						contentType : "application/json"
					},
					parameterMap : function(options, operation) {
						if (operation == "read") {
							var sort = [{dir:"desc",field:"create_time"}];
							if(options.sort!=null && options.sort.length>0 ){
								if(options.sort[0].field!="create_time"){
									options.sort[0].field="create_time";
								}
								
								sort=options.sort;
							}
							
							var parameter = {
								page : options.page, //当前页
								pageSize : options.pageSize,
								param:{
									name: $scope.search.activityName,
									state: $("#activityState").data("kendoDropDownList").value(),
									putaway: $("#taskUpOrDown").data("kendoDropDownList").value(),
									
									createTime_start: $("#startTime").val(),
									createTime_end: $("#endTime").val(),
									
									sort:sort
								}
							};
							console.log('查询参数',parameter);
							return kendo.stringify(parameter);
						}
					},
				},
				pageSize : 10,
				serverPaging : true,
				serverSorting: true,
				schema : {
					data : function(d) {
						return d.data;
					},
					total : function(d) {
						return d.total; //总条数
					}
				},
			},
			pageable : {  //分页
				pageSizes: [10, 20, 50, 100],  //每页显示记录数
			  },  
			sortable: {   //排序
				//allowUnsort: false,  //允许无序
			    mode: "single"     //排序模式：single，multiple
			  },
			editable: false,  //true：单个编辑；popup：弹出新页面编辑
			dataBound: function () {   //序号
		        var rows = this.items();
		        var page = this.pager.page() - 1;
		        var pagesize = this.pager.pageSize();
		        $(rows).each(function () {
		            var index = $(this).index() + 1 + page * pagesize;
		            var rowLabel = $(this).find(".row-number");
		            $(rowLabel).html(index);
		        });
		    },
			columns : [
					{    
						title : "序号",
						field : "id", 
						width : "50px",
						template:"<input type='checkbox' class='recordClass' value='#: id #' />"+"<span class='row-number subTitle'></span>"
					},
					{
						field : "name",         
						title : "活动名称",     
						width : "100px"
					},
					{
						field : "create_time",         
						title : "活动创建日期",     
						width : "100px"
					},
					{
						field : "start_time",         
						title : "活动进行周期",     
						width : "200px",
						template: function(e){
					    	return e.start_time+"-"+e.end_time;
					    }
					},
					{
						field : "putaway",         
						title : "上下架",     
						width : "100px",
						values: [
						         { text: "下架", value: 0 },
						         { text: "上架", value: 1 }
				        ],
					},
					{
						field : "state",         
						title : "状态",     
						width : "100px",
						values: [
						         { text: "未开始", value: 1 },
						         { text: "进行中", value: 2 },
						         { text: "已结束", value: 3 }
				        ],
					},
					{
						field : "",         
						title : "操作",     
						width : "100px",
						template: function(e){
					    	var html = '';
					    	
					    	html += '<div class="width_2 operation" ng-click="setActivityTask('+e.id+')">设置任务</div>';
					    	html += '<div class="width_2 operation" ng-click="taskList('+e.id+')">任务列表</div>';
					    	


					    	return html;
					    },
					}
			]
	};
	
	//查询
	$scope.search = function(){
		$scope.grid.dataSource.page(1);
	}
	
	//设置任务
	$scope.setActivityTask = function(activityId){
		$scope.form = {};
		$scope.form.activity_id = activityId;
		
		$scope.getGuiderData(activityId);	//获取导购
		$scope.getActivityInfo(activityId);			//获取活动信息
	}
	
	//任务列表
	$scope.taskList = function(id){
		var params = {activityId:id};
		$location.path("/taskList/"+angular.toJson(params));
	}
	
	//任务设置
	$scope.taskSetSubmit = function(){
		var shopIdArr = [];		//专卖店
		var guiderIdArr = [];	//导购
		
		var checkedNodes = guiderTree.ztree.getCheckedNodes(true);
    	$.each(checkedNodes, function(index, OneObj){
    		if(!OneObj.parent_id || OneObj.parent_id==0){
    			shopIdArr.push(OneObj.id);
    		}else{
    			guiderIdArr.push(OneObj.id);
    		}
		});
		
		$scope.form.user_userManager_tree = {	//专卖店，导购
				shop_id: shopIdArr,
				ids: guiderIdArr
		};	
		
		if(guiderIdArr.length==0){
			$scope.alertMessage("请选择导购人员！");
			return;
		}
		if(!$scope.form.activity_num){
			$scope.alertMessage("请输入活动成单数！");
			return;
		}else{
			if(!publicService.checkIsUpNumber($scope.form.activity_num)){
				$scope.alertMessage("活动成单数请输入正确的数值！");
				return;
			}
		}
		if(!$scope.form.sign_rate){
			$scope.alertMessage("请输入签到率！");
			return;
		}else{
			if($scope.form.sign_rate<0 || $scope.form.sign_rate>100){
				$scope.alertMessage("签到率区间为[0,100]！");
				return;
			}
		}
		
		$http({
			   url:  path+'/server/addUerManagerTaskBatch',
			   method: 'POST',   
			   data: angular.toJson($scope.form)
		}).success(function(data){
			if(data.code==0){
				$scope.activityTaskWindow.close();
				$scope.alertMessage("成功！");
			}else{
				$scope.alertMessage("失败！");
			}
		}).error(function(data){
			console.warn(data);   
		})
	}
	
	//获取导购
	$scope.getGuiderData = function(activityId){
		$http({
			   url: path+'/server/selectUserManagerTaskTree',
			   method: 'POST',   
			   data: angular.toJson({activity_id: activityId})
		}).success(function(data){
			if(data.code==0){
				guiderDataList = data.result;
				
				if(guiderDataList.length>0){
					guiderTree = publicService.initZtree("ztree",guiderDataList); 
					$scope.activityTaskWindow.center().open();   //打开弹框
				}else{
					$scope.alertMessage("该活动参与专卖店下所有导购人员已全部分配完毕！");
				}
			}else{
				console.log("失败！");
			}
		}).error(function(data){
			alert(data);   
		})
	}
	
	//获取活动信息
	$scope.getActivityInfo = function(activityId){
		$http({
			   url: path+'/server/selectActivityTime/'+activityId,
			   method: 'GET'
		}).success(function(data){
			if(data.code==0){
				var activityInfo = data.result;
				
				$scope.form.task_starttime = activityInfo.generalize_start;
				$scope.form.task_endtime = activityInfo.end_time;
			}else{
				console.log("失败！");
			}
		}).error(function(data){
			alert(data);   
		})
	}
	
	
	
	
	publicService.initActivityState("activityState");	//初始化【活动状态】
	publicService.initTaskUpOrDown("taskUpOrDown");		//初始化【任务上下架】
	publicService.initDateTime("startTime");	 //创建时间（始）
	publicService.initDateTime("endTime");		 //创建时间（止）

	
	
	
	
	
});